#
#  Copyright 2010 Andrew Kroh
#
#  Kroh-IO is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Kroh-IO is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import os
import sys
import platform

# Import the environment variables from calling script:
Import('env', 'AUTO_INCLUDE_DIR', 'LIB_KROHIO_INCLUDE_DIR')
Import('LIB_KROHIO_SRC_DIR', 'DIST_DIR', 'NATIVE_DIST_DIR')
Import('NATIVE_JAR_NAME')


# Clone the environment so changes 
# cannot affect global build env:
krohio_env = env.Clone()

krohio_env.Append(CPPPATH = [AUTO_INCLUDE_DIR, LIB_KROHIO_INCLUDE_DIR])


# This is to build a Univeral Library on Mac OS X:
# These flags are known to work on Mac OS X 10.6.
if sys.platform == 'darwin':
    arch_flags = '-arch i386 -arch ppc -arch x86_64'
    krohio_env.Append(CFLAGS = arch_flags)
    krohio_env.Append(LINKFLAGS = arch_flags)
elif sys.platform == 'win32':
    arch_flags = '/VERBOSE:lib'
    krohio_env.Append(LINKFLAGS = arch_flags)
    
# Using autoconf to account for platform differences:
autoconf = Configure(krohio_env)

# Not all platforms have cfmakeraw it is part of POSIX 1.1
# Added for Solaris.
if autoconf.CheckFunc('cfmakeraw'):
    print 'Found cfmakeraw() on system.'
    autoconf.env.Append(CFLAGS = '-DHAS_CFMAKERAW')
krohio_env = autoconf.Finish()

# Define the common source files to all architectures:
SOURCES = ['kroh_serial_port.c', 'util.c']

# Add the architecture specific source files:
if sys.platform == 'win32':
    print 'Including win32 specific source files.'
else:
    print 'Including posix specific source files.'
    SOURCES.append('posix_serial_port.c')
    SOURCES.append('cfmakeraw.c')

# Prepend the full path each source files:
SOURCE_PATHS = []
for x in SOURCES:
    SOURCE_PATHS.append(os.path.join(Dir(LIB_KROHIO_SRC_DIR).path, x))

# Create the shared library:
shared_lib_target = krohio_env.SharedLibrary('krohio', SOURCE_PATHS)

# ---------------------------------------------------------
# Create a Jar file containing the Native Library
# ---------------------------------------------------------
native_jar_target = krohio_env.Jar(
    target = os.path.join(Dir(DIST_DIR).path, NATIVE_JAR_NAME),
    source = [shared_lib_target],
    JARCHDIR = NATIVE_DIST_DIR + '/lib')
Depends(native_jar_target, shared_lib_target)
